//--------------------1、定义初始化变量--------------------
var myChart = echarts.init(document.getElementById('area-map'));
//存储切换的每一级地图信息
var areaMapData = [];
var maxValue = '';
var parent_code = $('#parent_code').val();
var parent_name = $('#parent_name').val();
var area_code = $('#area_code').val();
var area_name = $('#area_name').val();
var mapStack = [];
var timeFn = null;
var curMap = {};
var currentCity = '';
var code_name = '';
var mapcode1 = '';
var str1='';
var str2='';
var flag1='';
var domshow=document.getElementById('showButton')
//--------------------2、页面初始化--------------------
/**
 绑定用户切换地图区域事件
 cityMap对象存储着地图区域名称和区域的信息(name-code)
 当mapCode有值,说明可以切换到下级地图
 同时保存上级地图的编号和名称
 */
//flag:1:初始化、双击2:单击
if (parent_code != 0) {
    if ($("#aaa").val()=='07') {
        domshow.style.display = 'none';
    }
    getAreaMapData(parent_code, parent_name,1);
} else {
    mini.alert("区域地图无法显示,请联系管理员!");
}
//--------------------3、单击--------------------
/**
 * 绑定单击事件，并加载下一级地图
 */
myChart.on('click', function (params) {
    if ($("#aaa").val()=='07'){
        domshow.style.display='block';
    }
    clearTimeout(timeFn);
    //由于单击事件和双击事件冲突，故单击的响应事件延迟250毫秒执行
    timeFn = setTimeout(function () {
        var name = params.name;
        var mapCode = cityMap[name];
        if(mapCode===undefined){
            mini.alert("没有更详细的地图显示");
            return;
        }
        if (mapCode == area_code || area_code == parent_code || area_name == "市辖区") {
            if (!mapCode || mapStack.length > 0) {
                mini.alert("无此区域地图显示");
                return;
            }
            currentCity = name;
            getAreaMapData(mapCode, name,2);
            //将上一级地图信息压入mapStack
            mapStack.push({
                mapCode: curMap.mapCode,
                mapName: curMap.mapName
            });
        } else {
            mini.alert("您没有此查看权限");
        }

    }, 250);
});
//--------------------4、双击--------------------
/**
 绑定双击事件，并加载上一级地图
 */
myChart.on('dblclick', function (params) {
    //当双击事件发生时，清除单击事件，仅响应双击事件
    clearTimeout(timeFn);
    var map = mapStack.pop();
    if (!mapStack.length && !map) {
        mini.alert('已经到达最上一级地图了')
        return;
    }
    if ($("#aaa").val()=='07'){
        domshow.style.display='none';
    }
    getAreaMapData(map.mapCode, map.mapName,1);
});
//--------------------5、获取区域地图数据--------------------
/**
 * 获取区域地图数据
 * @param mapCode
 * @param mapName
 */
function getAreaMapData(mapCode, mapName,flag) {
    flag1=flag;
    $.ajax({
        url: "/main/selectAllDtNum?code=" + mapCode,
        type: "post",
        dataType: "json",
        success: function (data) {
            var rpData = data.data;
            if (rpData.length) {
                for (var i = 0, len = rpData.length; i < len; i++) {
                    if (rpData[i].name == area_name) {
                        rpData[i].selected = true;
                    }
                }
                areaMapData = rpData;
                var _cloneAreaMapData = JSON.stringify(rpData);
                var cloneAreaMapData = JSON.parse(_cloneAreaMapData);
                function compare(property) {
                    return function (a, b) {
                        var value1 = a[property];
                        var value2 = b[property];
                        return value2 - value1;
                    }
                }
                cloneAreaMapData.sort(compare("value"));
                maxValue = cloneAreaMapData[0].value;
                //初始化地图
                loadMap(mapCode, mapName,flag);
            }
        }
    });
}
//--------------------6、加载地图--------------------
/**
 加载地图：根据地图所在省市的行政编号，
 获取对应的json地图数据，然后向echarts注册该区域的地图
 最后加载地图信息
 @params {String} mapCode:地图行政编号,for example['中国':'100000', '湖南': '430000']
 @params {String} mapName: 地图名称
 */
function loadMap(mapCode, mapName,flag) {
    mapcode1 = mapCode;
    myChart = echarts.init(document.getElementById('area-map'));
    $.getJSON('/static/js/main-page/china-main-city/' + mapCode + '.json', function (data) {
        if (data) {
            //拿出需要的数据
            str1='';
            for(var i=0;i<data.features.length;i++){
                str1+=data.features[i].properties.adcode;
                if (i!=data.features.length-1){
                    str1+=',';
                }
            }
            if(flag==1 && parent_code!=area_code){
                var data1 = data.features;
                var size = data1.length-1;
                for(i=size;i>=0;i--){
                    if(area_name!=data1[i].properties.name){
                            data1.splice(i,1);
                    }
                }
            }
            echarts.registerMap(mapName, data);
            var option = {
                tooltip: {
                    show: true,
                    formatter: function (para) {
                        var str = '<div style="color:#05CFFE;font-size: 15px">' + para.name + '</div>';
                        if (area_name == parent_name || para.name == area_name || area_name == mapName || ("市辖区" == area_name && (parent_name == mapName || para.name == mapName))) {
                            if(undefined == para.data) {
                                $.ajax({
                                    url:encodeURI("/main/selectXinQv?name="+para.name+"&mapCode="+mapCode),
                                    cache: false,
                                    type:"POST",
                                    async:false,
                                    success: function (result) {
                                        result.data[0].count.forEach(function (item, index) {
                                            str += item.name + '：' + item.value + '人<br/>'
                                        });
                                        //$("#xinqv").val(str);
                                    }
                                });
                            }else{
                                para.data.count.forEach(function (item, index) {
                                    str += item.name + '：' + item.value + '人<br/>'
                                });
                            }
                        }
                        return str;
                    },
                },
                visualMap: {
                    show: true,
                    min: 0,
                    max: maxValue == 0 ? 10 : maxValue,
                    itemWidth: 10,
                    itemHeight: 50,
                    left: 30,
                    bottom: 20,
                    text: ['高', '低'], // 文本，默认为数值文本
                    calculable: true,
                    seriesIndex: [0],
                    inRange: {
                        color: ['#76c1ff', '#2d4cd9', '#120585'] // 蓝绿
                    }
                },
                /*工具按钮组*/
                toolbox: {
                    show: false,
                    orient: 'vertical',
                    left: 'right',
                    top: 'center',
                    feature: {
                        dataView: {
                            readOnly: false
                        },
                        restore: {},
                        saveAsImage: {}
                    }
                },
                series: [
                    {
                        name: '',
                        type: 'map',
                        map: mapName,
                        geoIndex: 0,
                        zoom: 1.2, //当前视角的缩放比例
                        roam: true, //是否开启平游或缩放
                        scaleLimit: { //滚轮缩放的极限控制
                            min: 0.6,
                            max: 3
                        },
                        layoutCenter: ['40%', '50%'],
                        layoutSize: '78%',
                        label: {
                            normal: {
                                show: true,
                                color: 'rgba(255,255,255,0.87)'
                            },
                            emphasis: {
                                show: true
                            }
                        },
                        itemStyle: {
                            normal: {
                                areaColor: '#dfdfdf',
                                borderColor: '#6a90d6'
                            },
                            emphasis: {
                                areaColor: '#ffb7b7'
                            }
                        },
                        data: areaMapData
                    }
                ]
            };
            myChart.setOption(option, true);
            curMap = {
                mapCode: mapCode,
                mapName: mapName
            };
            $('.currentCityStr').remove();

            if (mapName == 'china') {
                currentCity = "全国"
            } else {
                if(area_code==parent_code){
                    currentCity = mapName;
                } else {
                    currentCity = area_name;
                }

            }
            var currentCityStr = '<div class="currentCityStr" style="position:absolute;top: 10px;left: 15px;font-family:Microsoft Yahei">' +
                '<i class="iconfont icon-dingwei" style="color: #0d2ae5"></i> 当前地图显示：' +
                '<span style="color: rgb(18,5,133);font-size: 14px;font-weight: bold">' + (cityMap[mapCode] || currentCity) + '</span>' +
                '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<h5><font color="#808080">提示:鼠标双击地图返回上一级</font></h5></div>'
            $('#area-map').append(currentCityStr)
        } else {
            mini.alert("无法加载该地图");
        }
    });
}

// 获取地图上未显示新区的统计项
function wzsXinQv(){
    $.ajax({
        url: encodeURI("/main/selectWZSXinQv"),
        data: {'mapCode':mapcode1,'str1':str1},
        cache: false,
        type:"POST",
        success: function (result) {
            if (result.data.length!=0){
                var str='';
                for (var i=0;i<result.data.length;i++){
                    str+=result.data[i].name+"\n";
                    for (var j=0;j<result.data[i].count.length;j++){
                        str+=result.data[i].count[j].name + '：' + result.data[i].count[j].value + "人 。\n"
                    }
                }
                alert(str);
            }else {
                alert("该地图暂无新区！");
            }
        }
    });
}


